cc.Class({
    extends: cc.Component,

    properties: {
        rechargeWayItem: cc.Node,
        rechargeWayContent: cc.Node,


        recordItem: cc.Node,
        recordContent: cc.Node,
    },

    onEnable() {
        this.lobbyMain = cc.find("Canvas").getComponent("lobbyMain");
        this.lobbyNet = this.lobbyMain.lobbyNet;
        this.playerInfo = this.lobbyMain.playerInfo

        this.right = this.node.getChildByName("right");
        this.right2 = this.node.getChildByName("right2");
        this.canclePanel = this.node.getChildByName("cancleOrder");
        this.recordPanel = this.node.getChildByName("orderRecord");
        this.right.active = true;
        this.right2.active = false;
        this.canclePanel.active = false;
        this.recordPanel.active = false;

    },


    start() {
        this.amountEditBox = this.right.getChildByName("EditBox").getComponent(cc.EditBox)
        this.amountEditBox.enabled = false;
        this.rechargeWay = null;   //平台名
        this.rechargeType = null;  //充值方式
        this.recentOrder = null;
        this.url = "";

        this.giftCoin = 0
        this.lobbyMain.openLoading();
        this.getRechargeChannel(); //获取充值渠道
    },

    onClick(event, target) {
        if (target != "email" && target != "kefu") {
            this.lobbyMain.playClickSound();
        }
        if (target == "close") {
            this.lobbyMain.hidePanel(this.node);
        } else if (target == "email" || target == "kefu") {
            this.lobbyMain.onClick(event, target);
            this.node.getChildByName("top").getChildByName("btn_email").getChildByName("icon_ts").active = false;
        } else if (target == "5.99" || target == "9.99" || target == "19.99" || target == "49.99" || target == "99.99" || target == "149.99" || target == "199.99" || target == "299.99") {
            this.amountEditBox.string = target;
            this.giftCoin = 0
        } else if (target == "clean") {
            this.amountEditBox.string = "";
        } else if (target == "rechargeWay") {//选择充值平台
            this.rechargeWay = event.target.rechargeWay
        } else if (target == "recharge") {
            this.goRecharge();
        } else if (target == "bestValue") {
            let amount = event.target.getChildByName("label").getComponent(cc.Label).string;
            this.amountEditBox.string = amount;
            amount = parseFloat(amount);
            this.giftCoin = parseFloat((Math.floor(amount * 0.2 * 100) / 100).toFixed(2));
        } else if (target == "cancle") {  //取消订单
            this.showCancelPanel();
        } else if (target == "closeCancel") {  //取消订单
            this.canclePanel.getChildByName("confirm").getComponent(cc.Toggle).isChecked = false;
            this.lobbyMain.hidePanel(this.canclePanel);
        } else if (target == "ok" || target == "confirm") {   //OK或者确认取消
            this.changeIsOK(target);
        } else if (target == "read") {  //确认未充值
            let check = this.canclePanel.getChildByName("confirm").getComponent(cc.Toggle).isChecked;
            this.canclePanel.getChildByName("but_red").getComponent(cc.Button).interactable = check;
        } else if (target == "record") {  //查看历史订单
            this.getRechargeRecord();
        } else if (target == "close_record") {  //关闭历史订单
            let callback = () => {
                this.recordPanel.getChildByName('ScrollView').getChildByName('view').getChildByName('content').removeAllChildren();
            };
            this.lobbyMain.hidePanel(this.recordPanel, callback);
        } else if (target == "re_go") {  //关闭充值面板
            this.lobbyMain.openUrl(this.url);
        }
    },

    //获取充值订单返回
    onRechargeRecord(data) {
        this.lobbyMain.loading.active = false;
        console.log("获取充值订单返回:", data);
        if (data.respCode == "SUCCESS") {
            let info = data.data;
            info = this.sortByTimeDesc(info);  //排序
            for (let i = 0; i < info.length; i++) {
                const element = info[i];
                let item = cc.instantiate(this.recordItem);
                item.getChildByName("time").getComponent(cc.Label).string = this.formatWithLineBreak(element.time);
                item.getChildByName("method").getComponent(cc.Label).string = element.wayCode;
                item.getChildByName("amound").getComponent(cc.Label).string = element.amount;
                item.getChildByName("orderId").getComponent(cc.Label).string = element.orderId;
                item.getChildByName("orderId").getComponent(cc.Label).string = element.orderId;
                if (element.is_success) {
                    item.getChildByName("state").getChildByName("yes").active = true;
                } else {
                    item.getChildByName("state").getChildByName("no").active = true;
                }
                this.recordContent.addChild(item);
            }
            this.lobbyMain.showPanel(this.recordPanel);
        }
    },

    sortByTimeDesc(arr) {
        return arr.slice().sort((a, b) => new Date(b.time) - new Date(a.time));
    },


    //获取充值订单
    getRechargeRecord() {
        let data = {
            action: "getRechargeRecord",
            playerId: this.playerInfo.playerId,
        };
        this.lobbyNet.sendMessage(data);
        this.lobbyMain.openLoading();
    },


    //让订单不再显示
    changeIsOK(target) {
        this.handelRight2(false)
        this.right2.active = false;

        this.right.active = true;
        let data = {
            action: "changeIsOK",
            orderId: this.recentOrder[0].orderId,
            playerId: this.playerInfo.playerId,
        };
        this.lobbyNet.sendMessage(data);
        if (target == "confirm") {
            this.lobbyMain.hidePanel(this.canclePanel);
        }
    },

    //打开取消订单界面
    showCancelPanel() {
        this.canclePanel.getChildByName("but_red").getComponent(cc.Button).interactable = false;
        this.lobbyMain.showPanel(this.canclePanel);
    },

    // 获取充值渠道  和30分钟内的充值订单
    getRechargeChannel() {
        this.rechargeWayContent.removeAllChildren();
        let data = {
            action: "getRechargeChannel",
            playerId: this.playerInfo.playerId,
            agentId: this.playerInfo.agentId,
        };
        this.lobbyNet.sendMessage(data);
    },

    //获取充值通道返回  
    onRechargeChannel(data) {
        this.lobbyMain.loading.active = false;
        if (data.respCode == "SUCCESS") {
            let info = data.data.channels;
            for (let i = 0; i < info.length; i++) {
                const element = info[i];
                let item = cc.instantiate(this.rechargeWayItem);
                item.getChildByName("label").getComponent(cc.Label).string = element.type;
                this.rechargeWayContent.addChild(item);
                item.rechargeWay = element.name;
                item.rechargeType = element.type;
                if (i == 0) {
                    this.rechargeWay = element.name;
                    this.rechargeType = element.type;
                }
            }

            let recentOrder = data.data.recentOrders;
            this.recentOrder = recentOrder;
            if (recentOrder) {
                this.showRecentOrder(recentOrder);  // 显示最近30分钟的充值订单
            }
        } else {
            this.lobbyMain.showTips("Failed to retrieve top-up channels");
        }
    },


    //去充值
    goRecharge() {
        let amount = parseFloat(this.amountEditBox.string)
        if (isNaN(amount)) {
            this.lobbyMain.showTips("Please enter a valid amount!");
            return;
        }
        this.lobbyMain.openLoading();
        let playerId = this.playerInfo.playerId;
        let data = {
            rechargeWay: this.rechargeWay,
            rechargeType: this.rechargeType,
            amount: amount,
            playerId: playerId,
            giftCoin: this.giftCoin,
            isFirst: false,
        };
        this.lobbyNet.sendPost("recharge", data, (response) => {
            if (response.code == 0) {
                this.getRechargeChannel(); // 获取充值渠道
                this.lobbyMain.openUrl(response.data.cashierUrl);
            } else {
                let message;
                switch (response.code) {
                    case 10:
                        message = "System error";
                        break;
                    case 11:
                        message = "Invalid parameters";
                        break;
                    case 12:
                        message = "Signature error";
                        break;
                    case 13:
                        message = "Timestamp error";
                        break;
                    case 14:
                        message = "Duplicate submission";
                        break;
                    default:
                        if (response.code >= 200 && response.code < 300) {
                            message = "Business error";
                        } else if (response.code >= 300 && response.code < 400) {
                            message = "Channel error";
                        } else {
                            message = "Failed to initiate payment.";
                        }
                        break;
                }
                this.lobbyMain.showTips(message);
            }
        });
    },


    // 显示最近30分钟的充值订单
    showRecentOrder(data) {
        let info = data[0]
        this.right.active = false;
        this.right2.active = true;
        this.right2.getChildByName("orderId").getChildByName("label").getComponent(cc.Label).string = info.orderId;
        this.right2.getChildByName("ramount").getChildByName("label").getComponent(cc.Label).string = info.amount;
        this.url = info.url;


        if (info.is_success) {
            this.handelRight2(true);
        }

    },

    // 处理现有订单的情况


    handelRight2(bool) {
        const jindu = this.right2.getChildByName("jindu");
        const taskPro2 = jindu.getChildByName("task_pro2").getComponent(cc.ProgressBar);
        const successJinduOk = jindu.getChildByName("success").getChildByName("jindu_ok");
        const endJinduOk = jindu.getChildByName("end").getChildByName("jindu_ok");

        const state1 = this.right2.getChildByName("state1");
        const state2 = this.right2.getChildByName("state2");
        const butRed = this.right2.getChildByName("but_red");
        const butGo = this.right2.getChildByName("but_go");
        const butOk = this.right2.getChildByName("but_ok");

        // 根据 bool 设置进度条
        taskPro2.progress = bool ? 1 : 0;

        // 根据 bool 显示/隐藏节点
        successJinduOk.active = bool;
        endJinduOk.active = bool;
        state1.active = !bool;
        state2.active = bool;
        butRed.active = !bool;
        butGo.active = !bool;
        butOk.active = bool;
    },

    // 格式化日期字符串
    formatWithLineBreak(isoString) {
        return isoString.replace("T", "\n").replace("Z", "").slice(0, 19);
    },




    // update (dt) {},
});
